package com.bac.rentmap.web.controller.ad.user.review;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Required;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.bac.rentmap.ad.flat.FlatAd;
import com.bac.rentmap.ad.flat.FlatAdDao;
import com.bac.rentmap.ad.flat.user.review.ReviewCountIncrementer;
import com.bac.rentmap.web.ad.user.review.UserReviewHelper;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

/**
 * Increase user review counter for specific review type (agent, badPhone,
 * expiredAd) in case user has not add review before.
 * 
 * @author Andrei_Asipenka
 */
public class UserReviewController extends AbstractController {
    public static final String USER_REVIEW_THANK_YOU = "showUserReviewThankYou";
  
	private static final Logger log = Logger
			.getLogger(UserReviewController.class.getName());

	private ReviewCountIncrementer reviewCountIncrementer;
	private FlatAdDao flatAdDao;

	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Long flatAdId = Long.valueOf(request.getParameter("flatAdId"));
		Map<String, Object> model = new HashMap<String, Object>();
		FlatAd flatAd = flatAdDao.get(flatAdId);
		Set<String> reviewers = flatAd.getReviewers();
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		if (user != null && (reviewers == null || !reviewers.contains(user.getEmail()))) {
		  flatAd = reviewCountIncrementer.inc(flatAdId, user.getEmail()); 
		}
		String redirectUrl = request.getParameter("redirectUrl");
		if (redirectUrl != null) {
			log.fine("Redirect URL: " + redirectUrl);
			addCookie(response);
			response.sendRedirect(redirectUrl);
			return null;
		} else {
			model.put("flatAd", flatAd);
      model.put(USER_REVIEW_THANK_YOU, true);
			return new ModelAndView("ad/search/review/flatReview", model);
		}
	}
	
	private void addCookie(HttpServletResponse response){
	    Cookie cookie = new Cookie(USER_REVIEW_THANK_YOU, "true");
	    cookie.setPath("/");
	    response.addCookie(cookie);
	}

	@Required
	public void setFlatAdDao(FlatAdDao flatAdDao) {
		this.flatAdDao = flatAdDao;
	}

	@Required
	public void setReviewCountIncrementer(
			ReviewCountIncrementer reviewCountIncrementer) {
		this.reviewCountIncrementer = reviewCountIncrementer;
	}
}
